package org.codingq92.network;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * @author: CodingQ92
 * @date: 2025/6/17 21:47
 */
public class UDPDemo {
    public static void main(String[] args) {
        // 启动UDP Server服务
        new Thread(UDPDemo::udpServer).start();
        // 启动UDP Client服务
        new Thread(UDPDemo::udpClient).start();
    }

    private static void udpClient() {
        try (DatagramSocket client = new DatagramSocket()) {
            for (int i = 0; i < 10; i++) {
                byte[] content = ("hello_" + i).getBytes(); // 数据
                InetAddress localHost = InetAddress.getLocalHost(); // 目标地址
                DatagramPacket packet = new DatagramPacket(content, content.length, localHost, 18000); // 包
                client.send(packet); // 发送
                System.out.println("发送了数据：" + new String(content));
                Thread.sleep(1000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void udpServer() {
        try (DatagramSocket server = new DatagramSocket(18000)) {
            byte[] buffer = new byte[1024 * 64]; // 接收数据大小 UDP 最大就是64KB
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
            while (true) {
                server.receive(packet);
                InetAddress address = packet.getAddress();
                byte[] packetData = packet.getData();
                String msg = new String(packetData, 0, packet.getLength());
                System.out.println("从[" + address.getHostAddress() + ":" + packet.getPort() + "]接受到数据: " + msg);
                Thread.sleep(1000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
